cmake_minimum_required(VERSION 2.8)
project(lua)

set(SRC_PATH src)

file(GLOB HEADERS ${SRC_PATH}/src/*.h)
set(SOURCES
    ${SRC_PATH}/lapi.c
    ${SRC_PATH}/lcode.c
    ${SRC_PATH}/ldebug.c
    ${SRC_PATH}/lgc.c
    ${SRC_PATH}/lmathlib.c
    ${SRC_PATH}/lopcodes.c
    ${SRC_PATH}/lstring.c
    ${SRC_PATH}/ltm.c
    ${SRC_PATH}/lutf8lib.c
    ${SRC_PATH}/lauxlib.c
    ${SRC_PATH}/lcorolib.c
    ${SRC_PATH}/ldo.c
    ${SRC_PATH}/linit.c
    ${SRC_PATH}/lmem.c
    ${SRC_PATH}/loslib.c
    ${SRC_PATH}/lstrlib.c
    ${SRC_PATH}/lvm.c
    ${SRC_PATH}/lbaselib.c
    ${SRC_PATH}/lctype.c
    ${SRC_PATH}/ldump.c
    ${SRC_PATH}/liolib.c
    ${SRC_PATH}/loadlib.c
    ${SRC_PATH}/lparser.c
    ${SRC_PATH}/ltable.c
    ${SRC_PATH}/lzio.c
    ${SRC_PATH}/lbitlib.c
    ${SRC_PATH}/ldblib.c
    ${SRC_PATH}/lfunc.c
    ${SRC_PATH}/llex.c
    ${SRC_PATH}/lobject.c
    ${SRC_PATH}/lstate.c
    ${SRC_PATH}/ltablib.c
    ${SRC_PATH}/lundump.c
)
add_library(lualib
    ${HEADERS}
    ${SOURCES}
    )
target_include_directories(lualib PUBLIC ${SRC_PATH})
set_target_properties(lualib
    PROPERTIES
    OUTPUT_NAME lua)


add_executable(lua
    ${SRC_PATH}/lua.c
    )
target_link_libraries(lua PUBLIC lualib)

add_executable(luac
    ${SRC_PATH}/luac.c
    ${SOURCES}
    )

if(WIN32)
    if(${BUILD_SHARED_LIBS})
        target_compile_definitions(lualib PUBLIC LUA_BUILD_AS_DLL)
    endif()
    #target_compile_definitions(lualib PUBLIC LUA_USE_WINDOWS)
    #target_compile_definitions(luac PUBLIC LUA_USE_WINDOWS)
    #target_compile_definitions(lualib PUBLIC LUA_DL_DLL)
endif()


if(WIN32)
else()
    #target_compile_definitions(lualib PUBLIC LUA_USE_DLOPEN)
    #target_link_libraries(lualib PUBLIC dl)
    #target_link_libraries(lualib PUBLIC m)
    #target_link_libraries(luac PUBLIC m)
endif()

if(LINUX)
    target_compile_definitions(lualib PUBLIC LUA_USE_LINUX)
    target_link_libraries(lualib PUBLIC dl)
    target_link_libraries(luac PUBLIC dl)
    target_compile_definitions(luac PUBLIC LUA_USE_LINUX)

    find_library(M_LIBRARY NAMES m)
    if(NOT M_LIBRARY)
        message(FATAL_ERROR "libm not founded.")
    else()
        target_link_libraries(lualib PUBLIC ${M_LIBRARY})
        target_link_libraries(luac PUBLIC m)
    endif()

    find_library(READLINE_LIBRARY
        NAMES readline)
    if(NOT READLINE_LIBRARY)
        message(STATUS "libreadline not found;")
    else()
        target_link_libraries(lua PUBLIC ${READLINE_LIBRARY})
    endif()
endif()


if(MACOSX)
    target_compile_definitions(lualib PUBLIC LUA_USE_MACOSX)
    target_link_libraries(lua PUBLIC readline)
    target_compile_definitions(luac PUBLIC LUA_USE_LINUX)
endif()

if(ANDROID)
    target_compile_definitions(lualib PUBLIC LUA_USE_DLOPEN)
    target_compile_definitions(lualib PUBLIC LUA_USE_POSIX)
    target_link_libraries(lualib PUBLIC dl)
endif()
